package name.zeno.qrcode.library

import android.app.Activity
import android.app.Fragment
import android.content.Context
import io.reactivex.Observable
import name.zeno.ktrxpermission.ZPermission
import name.zeno.ktrxpermission.rxPermissions

/**
 * @author 陈治谋 (513500085@qq.com)
 * @since 2017/12/5
 */

fun Fragment.qrcodeFromAlbum(): Observable<String> =
    AlbumFragment.with(this).fromAlbum().map { QRCodeUtil.decode(it) ?: error("识别图中二维码不成功") }

fun Activity.qrcodeFromAlbum(): Observable<String> =
    AlbumFragment.with(this).fromAlbum().map { QRCodeUtil.decode(it) ?: error("识别图中二维码不成功") }


fun Fragment.navQrcode(onResult: ((ok: Boolean, data: QRCode?) -> Unit)) {
  rxPermissions(ZPermission.CAMERA).subscribe {
    if (!it) return@subscribe

    NavFragment.with(this).navForResult(QRCodeReaderActivity::class.java) { ok, data ->
      onResult(ok, data?.getParcelableExtra("data"))
    }
  }
}

fun Activity.navQrcode(onResult: ((ok: Boolean, data: QRCode?) -> Unit)) {
  rxPermissions(ZPermission.CAMERA).subscribe {
    if (!it) return@subscribe

    NavFragment.with(this).navForResult(QRCodeReaderActivity::class.java) { ok, data ->
      onResult(ok, data?.getParcelableExtra("data"))
    }
  }
}

fun Context.navAppDetail() {

}

